/*
 *  Copyright (c) 2009 Baturu.COM
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.baturu.oss.dao.jpa;

import com.baturu.oss.dao.OpenLinkDAO;
import com.baturu.oss.entities.links.OpenLink;
import org.sitevelocity.exceptions.NoSuchEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author javafuns
 */
public class OpenLinkDAOImpl implements OpenLinkDAO {

    private PersistenceManager pm;

    public OpenLinkDAOImpl(PersistenceManager pm) {
        this.pm = pm;
    }

    public PersistenceManager getPersistenceManager() {
        return this.pm;
    }

    @Override
    public OpenLink newLink(OpenLink openLink) {
        return pm.makePersistent(openLink);
    }

    @Override
    public void updateLink(OpenLink openLink) throws NoSuchEntityException {
        if (this.getLink(openLink.getId()) == null) {
            throw new NoSuchEntityException("The openLink with id " + openLink.getId() + " no longer exists.");
        }
        openLink = pm.makePersistent(openLink);
    }

    @Override
    public void removeLink(String id) {
        pm.deletePersistent(this.getLink(id));
    }

    @Override
    public List<OpenLink> findLinks(int maxResults, int firstResult, String orderByDesc) {
        Query query = pm.newQuery("select from " + OpenLink.class.getName());
        if (maxResults >= 0) {
            if (firstResult < 0) {
                firstResult = 0;
            }
            query.setRange(firstResult, firstResult + maxResults);
        }
        if (orderByDesc == null || "".equals(orderByDesc)) {
            orderByDesc = "id asc";
        }
        query.setOrdering(orderByDesc);
        List<OpenLink> ols = (List<OpenLink>) query.execute();
        return (ols==null?new ArrayList<OpenLink>(0):ols);
    }

    @Override
    public OpenLink getLink(String id) {
        return pm.getObjectById(OpenLink.class, id);
    }

    @Override
    public int getLinkCount() {
        String querySQL = "select count(id) from " + OpenLink.class.getName();
        Query query = this.pm.newQuery(querySQL);
        Number count = (Number) query.execute();
        return count.intValue();
    }
}
